/*
 * Copyright (C) 2021 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

#include "aht20.h"
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/i2c.h"

void Aht20TestTask(void *arg)
{
    (void)arg;
    uint32_t retval = 0;

    i2c_config_t i2c_initer = {
        .clk_flags = 0,            // 选择默认时钟源
        .master.clk_speed = 50000, // 指定速率为100Kbit,最大可以为400Kbit
        .mode = I2C_MODE_MASTER,   // 主机模式
        .scl_io_num = 22,          // 指定SCL的GPIO口
        .scl_pullup_en = true,     // SCL接上拉电阻
        .sda_io_num = 21,          // 指定SDA的GPIO口
        .sda_pullup_en = true,     // SDA接上拉电阻
    };

    printf("sda_io_num  is %d scl_io_num %d\r\n", i2c_initer.sda_io_num, i2c_initer.scl_io_num);

    printf("Aht20Task %s %d\r\n", __FILE__, __LINE__);
    if (i2c_param_config(I2C_NUM_0, &i2c_initer) == ESP_OK)
    {
        printf("i2c parm config success\r\n");
    }
    else
    {
        printf("config fail\r\n");
    }

    printf("Aht20Task %s %d\r\n", __FILE__, __LINE__);

    if (i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0) == ESP_OK)
    {
        printf("i2c driver install success\r\n");
    }
    else
    {
        printf("driver fail\r\n");
    }

    printf("Aht20Task %s %d\r\n", __FILE__, __LINE__);
    retval = AHT20_Calibrate();

    printf("Aht20Task %s %d\r\n", __FILE__, __LINE__);
    printf("AHT20_Calibrate: %d\r\n", retval);

    while (1)
    {
        float temp = 0.0, humi = 0.0;

        retval = AHT20_StartMeasure();
        printf("AHT20_StartMeasure: %d\r\n", retval);

        retval = AHT20_GetMeasureResult(&temp, &humi);
        if (retval == 0)
        {
            printf("AHT20_GetMeasureResult: %d, temp = %.2f, humi = %.2f\r\n", retval, temp, humi);
        }

        sleep(1);
    }
}

void Aht20Test(void)
{
    osThreadAttr_t attr;

    printf("Aht20Task\r\n");

    attr.name = "Aht20Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew(Aht20TestTask, NULL, &attr) == NULL)
    {
        printf("[Aht20Test] Failed to create Aht20TestTask!\n");
    }
}

OHOS_APP_RUN(Aht20Test);
